package com.szzg10.webservice.chapter5;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.http.HTTPException;

@WebService(endpointInterface = "com.szzg10.webservice.chapter5.TempConvert")
public class TempConvertImpl implements TempConvert {

	@Resource
	private WebServiceContext webServiceContext;
	
	@Override
	@WebMethod
	public float c2f(float t) {
		authenticate();
		return 32.0f + (t * 9.0f / 5.0f);
	}

	@Override
	@WebMethod
	public float f2c(float t) {
		authenticate();
		return (5.0f / 9.0f) * (t -32.0f);
	}
	
	private void authenticate() {
		MessageContext messageContext = webServiceContext.getMessageContext();
		Map<String, List<String>> headers = (Map<String, List<String>>)messageContext.get(MessageContext.HTTP_REQUEST_HEADERS);
		
		String userName = headers.get(BindingProvider.USERNAME_PROPERTY).get(0);
		String password = headers.get(BindingProvider.PASSWORD_PROPERTY).get(0);
		
		if(!userName.equals("fred") || !password.equals("rockbed")) {
			throw new HTTPException(401);
		}
	}

}
